﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PowerBooking.RSE.IRepository;
using System.Transactions;

namespace PowerBooking.RSE.Repository
{
    /// <summary>
    /// 工作单元
    /// </summary>
    public class UnitOfWork : IUnitOfWork
    {
        private DataContext dataContext;
        private readonly Lazy<SpiderRepository> spiderRepository;
        private readonly Lazy<CityRepository> cityRepository;
        private readonly Lazy<FilterRepository> filterRepository;
        private readonly Lazy<RestaurantRepository> restaurantRepository;

        public ISpiderRepository SpiderRepository { get { return spiderRepository.Value; } }
        public ICityRepository CityRepository { get { return cityRepository.Value; } }
        public IFilterRepository FilterRepository { get { return filterRepository.Value; } }
        public IRestaurantRepository RestaurantRepository { get { return restaurantRepository.Value; } }

        public UnitOfWork()
        {
            dataContext = new DataContext();

            spiderRepository = new Lazy<SpiderRepository>(() => new SpiderRepository(dataContext));
            cityRepository = new Lazy<CityRepository>(() => new CityRepository(dataContext));
            filterRepository = new Lazy<FilterRepository>(() => new FilterRepository(dataContext));
            restaurantRepository = new Lazy<RestaurantRepository>(() => new RestaurantRepository(dataContext));
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    dataContext.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Save()
        {
            dataContext.SaveChanges();
        }
    }
}
